package com.remotephone.myapplication

import android.app.*
import android.content.Intent
import android.os.*
import android.util.Log
import androidx.core.app.NotificationCompat
import java.io.*

class SystemScreenshotService : Service() {
    
    private val binder = ScreenshotBinder()
    
    // 回调接口
    interface ScreenshotCallback {
        fun onScreenshotTaken(path: String?)
    }
    
    companion object {
        private const val TAG = "SystemScreenshot"
        private const val NOTIFICATION_ID = 4
        private const val CHANNEL_ID = "system_screenshot_channel"
        
        const val ACTION_TAKE_SCREENSHOT = "TAKE_SCREENSHOT"
        
        private var callback: ScreenshotCallback? = null
        
        fun setCallback(cb: ScreenshotCallback?) {
            callback = cb
        }
    }
    
    inner class ScreenshotBinder : Binder() {
        fun getService(): SystemScreenshotService = this@SystemScreenshotService
    }
    
    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
    }
    
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startForeground(NOTIFICATION_ID, createNotification())
        
        when (intent?.action) {
            ACTION_TAKE_SCREENSHOT -> {
                takeSystemScreenshot()
            }
        }
        
        return START_STICKY
    }
    
    override fun onBind(intent: Intent?): IBinder = binder
    
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "系统截图服务",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "使用系统命令处理屏幕截图"
            }
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }
    
    private fun createNotification(): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("系统截图服务运行中")
            .setContentText("准备系统级截图")
            .setSmallIcon(android.R.drawable.ic_menu_camera)
            .setOngoing(true)
            .build()
    }
    
    private fun takeSystemScreenshot() {
        Log.d(TAG, "Starting system screenshot...")
        
        Thread {
            try {
                // 方案1: 使用screencap命令（需要shell权限）
                val timestamp = System.currentTimeMillis()
                val outputPath = "${cacheDir}/screenshots/system_screenshot_$timestamp.png"
                
                // 确保目录存在
                File("${cacheDir}/screenshots/").mkdirs()
                
                // 执行screencap命令
                val process = Runtime.getRuntime().exec("screencap -p $outputPath")
                val exitCode = process.waitFor()
                
                if (exitCode == 0) {
                    Log.d(TAG, "System screenshot success: $outputPath")
                    callback?.onScreenshotTaken(outputPath)
                } else {
                    Log.e(TAG, "System screenshot failed with exit code: $exitCode")
                    // 方案2: 尝试其他路径
                    tryAlternativeScreenshot()
                }
                
            } catch (e: Exception) {
                Log.e(TAG, "Error taking system screenshot", e)
                tryAlternativeScreenshot()
            }
        }.start()
    }
    
    private fun tryAlternativeScreenshot() {
        try {
            // 方案2: 模拟系统截图快捷键（需要无障碍权限）
            Log.d(TAG, "Trying alternative screenshot method...")
            
            // 这里可以尝试其他方法，比如：
            // 1. 发送系统广播
            // 2. 调用系统截图服务
            // 3. 使用无障碍服务模拟按键
            
            val timestamp = System.currentTimeMillis()
            sendBroadcast(Intent("android.intent.action.TAKE_SCREENSHOT"))
            
            // 等待一段时间检查系统截图目录
            Handler(Looper.getMainLooper()).postDelayed({
                checkSystemScreenshotDir()
            }, 2000)
            
        } catch (e: Exception) {
            Log.e(TAG, "Alternative screenshot method failed", e)
            callback?.onScreenshotTaken(null)
        }
    }
    
    private fun checkSystemScreenshotDir() {
        try {
            // 检查常见的系统截图目录
            val possibleDirs = listOf(
                "/sdcard/Pictures/Screenshots/",
                "/sdcard/DCIM/Screenshots/",
                "/storage/emulated/0/Pictures/Screenshots/",
                "/storage/emulated/0/DCIM/Screenshots/"
            )
            
            var latestScreenshot: File? = null
            var latestTime = 0L
            
            for (dirPath in possibleDirs) {
                val dir = File(dirPath)
                if (dir.exists() && dir.isDirectory) {
                    val files = dir.listFiles { file ->
                        file.name.endsWith(".png") || file.name.endsWith(".jpg")
                    }
                    
                    files?.forEach { file ->
                        if (file.lastModified() > latestTime) {
                            latestTime = file.lastModified()
                            latestScreenshot = file
                        }
                    }
                }
            }
            
            // 检查是否是最近1分钟内的截图
            val screenshot = latestScreenshot
            if (screenshot != null && 
                System.currentTimeMillis() - latestTime < 60000) {
                Log.d(TAG, "Found recent screenshot: ${screenshot.absolutePath}")
                callback?.onScreenshotTaken(screenshot.absolutePath)
            } else {
                Log.e(TAG, "No recent screenshot found in system directories")
                callback?.onScreenshotTaken(null)
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "Error checking system screenshot directory", e)
            callback?.onScreenshotTaken(null)
        }
    }
} 